package com.zhongkai.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.Bean.WebSocketIndBean;
import com.zhongkai.MessageTool;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.app.service.SellService;
import com.zhongkai.listener.RocketMqProducer;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.Sell;
import com.zhongkai.model3.SetProduct;
import com.zhongkai.model3.Warehouse3;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.regex.Pattern;

/**
 * 销售新增
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class SellServiceImpl implements SellService {


    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;


    @Autowired
    private RocketMqProducer rocketMqProducer;
/*    @Autowired
    private JmsTemplate jmsTemplate;

    @Resource
    private Destination topicDestination;*/

    /**
     * 销售添加
     *
     * @param sell_uuid   订单编号
     * @param set_uuid    产品编号
     * @param sell_name   产品名称
     * @param sell_price  单价
     * @param sell_count  数量
     * @param sell_sum    总价
     * @param sell_client 客户姓名
     * @param sell_number 合同编号
     * @param sell_member 销售人员姓名
     * @param member_uuid 销售人员uuid
     */
    @Override
    public ZhongkaiResult addSell(String sell_uuid, String set_uuid, String sell_name, String sell_price,
                                  String sell_count, String sell_sum, String sell_client, String sell_number,
                                  String sell_member, String member_uuid) {

        if (StringUtils.isNullOrEmpty(set_uuid) || StringUtils.isNullOrEmpty(sell_name)
                || StringUtils.isNullOrEmpty(sell_price) || StringUtils.isNullOrEmpty(sell_count)
                || StringUtils.isNullOrEmpty(sell_sum) || StringUtils.isNullOrEmpty(sell_client)
                || StringUtils.isNullOrEmpty(sell_number) || StringUtils.isNullOrEmpty(sell_member)
                || StringUtils.isNullOrEmpty(member_uuid)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        Sell sell;

        sell = (Sell) iBaseDao.get("from Sell se where se.sellNumber='" + sell_number + "'");

        if (sell != null) {
            return ZhongkaiResult.build(400, "合同编号重复提交，请检查");
        }


        sell = new Sell();


        boolean count = isInteger(sell_count);

        if (!count) {
            return ZhongkaiResult.build(400, "订单数量请输入整数");
        }


        //公司产品库
        Warehouse3 warehouse = (Warehouse3) iBaseDao.get("from Warehouse3 wa where wa.warName='" + sell_name + "'");

        if (warehouse == null) {
            return ZhongkaiResult.build(500, "此产品不存在");
        }

        Integer warCount1 = warehouse.getWarCount();

        //  System.out.println(warCount1+"addSell");
        if (warCount1 <= 0) {

            return ZhongkaiResult.build(400, "库存不足");
        }


        int counts = warehouse.getWarCount() - Integer.parseInt(sell_count);
        // System.out.println(counts+"addSell");
        if (counts >= 0) {
            warehouse.setWarCount(counts);
        } else {
            return ZhongkaiResult.build(400, "库存不足");

        }


        sell.setSellUuid(sell_uuid);

        sell.setSetUuid(warehouse.getWarUuid());
        sell.setSellName(warehouse.getWarName());


        sell.setSellPrice(sell_price);
        sell.setSellCount(Integer.parseInt(sell_count));//此处可能报错 注意
        sell.setSellSum(sell_sum);
        sell.setSellClient(sell_client);
        sell.setSellNumber(sell_number);//合同编号 不可重复
        sell.setSellMember(sell_member);
        sell.setMemberUuid(member_uuid);


        sell.setSellStatus(1); // 1待审核 2已审核 3被驳回
        sell.setIsOut("1"); //1未出库 2已出库
        sell.setSellRemove("1"); //1未删除 2已删除

        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        sell.setSellTime(millis); //订单创建时间


        try {
            iBaseDao.save(sell);
            iBaseDao.update(warehouse);
            WebSocketIndBean indBean = new WebSocketIndBean();
            indBean.setUser_uuid("null");
            indBean.setType("-2");
            indBean.setContent("您有新的销售订单申请,请尽快审核~");

            ObjectMapper mapper = new ObjectMapper();

            String json = mapper.writeValueAsString(indBean);
            byte[] bytes = json.getBytes("utf-8");
            rocketMqProducer.sendMsgIntime(MessageTool.BIG_SKY, MessageTool.FWEB_DATE, bytes);


/*            jmsTemplate.send(topicDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {



                    TextMessage textMessage = session.createTextMessage(json);
                    return textMessage;
                }
            });*/


            return ZhongkaiResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "添加失败");
        }

    }


    /**
     * 销售修改
     *
     * @param sell_uuid   订单编号
     * @param set_uuid    产品编号
     * @param sell_name   产品名称
     * @param sell_price  单价
     * @param sell_count  数量
     * @param sell_sum    总价
     * @param sell_client 客户姓名
     * @param sell_number 合同编号
     */
    @Override
    public ZhongkaiResult updateSell(String sell_uuid, String set_uuid, String sell_name, String sell_price, String sell_count, String sell_sum, String sell_client, String sell_number) {
        if (StringUtils.isNullOrEmpty(set_uuid) || StringUtils.isNullOrEmpty(sell_name)
                || StringUtils.isNullOrEmpty(sell_price) || StringUtils.isNullOrEmpty(sell_count)
                || StringUtils.isNullOrEmpty(sell_sum) || StringUtils.isNullOrEmpty(sell_client)
                || StringUtils.isNullOrEmpty(sell_number) || StringUtils.isNullOrEmpty(sell_uuid)) {

            return ZhongkaiResult.build(400, "数据不完整");
        }


        Sell sell;
        Sell sell2;

        sell = (Sell) iBaseDao.get("from Sell se where se.sellUuid='" + sell_uuid + "'");
        sell2 = (Sell) iBaseDao.get("from sell se where se.sellNumber='" + sell_number + "'");

        if (sell == null) {
            return ZhongkaiResult.build(400, "此订单不存在");
        }

/*        if (sell2 != null) {
            return ZhongkaiResult.build(400,"合同编号重复提交，请检查");
        }*/


        boolean count = isInteger(sell_count);

        if (!count) {
            return ZhongkaiResult.build(400, "订单数量请输入整数");
        }

        //公司产品库
        Warehouse3 warehouse = (Warehouse3) iBaseDao.get("from Warehouse3 wa where wa.warName='" + sell_name + "'");
        if (warehouse == null) {
            return ZhongkaiResult.build(500, "此产品不存在");
        }
        Integer warCount1 = warehouse.getWarCount();

        //  System.out.println(warCount1+"addSell");
        if (warCount1 <= 0) {

            return ZhongkaiResult.build(400, "库存不足");
        }

        int counts = warehouse.getWarCount() - Integer.parseInt(sell_count);
        // System.out.println(counts+"addSell");
        if (counts >= 0) {
            warehouse.setWarCount(counts);
        } else {
            return ZhongkaiResult.build(400, "库存不足");

        }

        iBaseDao.update(warehouse);

        sell.setSellUuid(sell_uuid);
        sell.setSetUuid(set_uuid);
        sell.setSellName(sell_name);
        sell.setSellPrice(sell_price);
        sell.setSellCount(Integer.parseInt(sell_count));//此处可能报错 注意
        sell.setSellSum(sell_sum);
        sell.setSellClient(sell_client);
        sell.setSellNumber(sell_number);//合同编号 不可重复

        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        sell.setSellTime(millis); //订单创建时间

        sell.setSellStatus(1); // 1待审核 2已审核 3被驳回
        sell.setIsOut("1"); ////1未出库 2已出库

        if (sell2 == null) {

            iBaseDao.update(sell);
            return ZhongkaiResult.ok();

        } else {
            if (sell2.getSellNumber().equals(sell.getSellNumber())) { //如果合同编号与本次修改的编号一致 更新
                try {
                    iBaseDao.update(sell);
                    return ZhongkaiResult.ok();
                } catch (Exception e) {
                    e.printStackTrace();
                    return ZhongkaiResult.build(400, "添加失败");
                }
            } else {

                return ZhongkaiResult.build(400, "合同编号重复提交，请检查");
            }
        }

    }


    //删除订单
    @Override
    public ZhongkaiResult removeSell(String sell_uuid) {

        if (StringUtils.isNullOrEmpty(sell_uuid)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        Sell sell;

        sell = (Sell) iBaseDao.get("from Sell se where se.sellUuid='" + sell_uuid + "'");

        if (sell == null) {
            return ZhongkaiResult.build(400, "此订单不存在");
        }

        if (sell.getSellStatus() == 2) {
            return ZhongkaiResult.build(400, "已审批订单不可删除");
        }


        if ("2".equals(sell.getIsOut())) {
            return ZhongkaiResult.build(400, "已入库订单不可删除");
        }

        Warehouse3 warehouse = (Warehouse3) iBaseDao.get("from Warehouse3 wa where wa.warUuid='" + sell.getSetUuid() + "'");

        if (warehouse != null) {
            int i = warehouse.getWarCount() + sell.getSellCount();//修改库存
            warehouse.setWarCount(i);
            iBaseDao.update(warehouse);

        }
/*        sell.setSellRemove("2"); //1未删除 2已删除
        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        sell.setRemoveTime(millis); //订单创建时间*/
        iBaseDao.delete(sell);
        return ZhongkaiResult.ok();

    }

    @Override
    public ZhongkaiResult listSell(Integer page, Integer rows) {

        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Sell.class);
            detachedCriteria.add(Restrictions.eq("sellRemove", "1")); //增加条件
            detachedCriteria.addOrder(Order.desc("sellTime")); //根据传入的字段进行降序排序
            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }


    /*速度最快
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */

    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
}
